<?php

namespace app\model;

use think\Model;
use think\facade\Db;

class User extends Model
{
    // 表名
    protected $name = 'lucky_user';
    // 主键
    protected $pk = 'id';
    // 自动写入时间戳
    protected $autoWriteTimestamp = 'timestamp';

    public function prize()
    {
        return $this->hasOne(Prize::class, 'id', 'prize_id');
    }

    /**
     * 获取用户列表，支持分页和条件筛选
     * @param array $where 筛选条件
     * @param array $order 排序条件
     * @param int $page 页码
     * @param int $limit 每页数量
     * @return array 返回包含数据列表、总条数、是否有下一页的数组
     */
    public static function getUserList($page = 1, $limit = 10, $where = [], $order = ['id' => 'asc'])
    {
        $query = self::where($where);

        // 获取总条数
        $total = $query->count();

        // 获取当前页数据
        $list = $query->with(['prize'])
            ->order($order)
            ->page($page, $limit)
            ->select();

        // 判断是否有下一页
        $hasMore = ($page * $limit) < $total;

        return [
            'list' => $list,
            'total' => $total,
            'hasMore' => $hasMore
        ];
    }

    /**
     * 获取未中奖用户列表
     */
    public static function getNonWinners($page = 1, $limit = 10)
    {
        return self::where('is_winner', 0)
            ->order('id RAND()')
            ->page($page, $limit)
            ->select();
    }

    /**
     * 获取已中奖用户列表
     */
    public static function getWinners($page = 1, $limit = 10)
    {
        return self::where('is_winner', 1)
            ->order('id ASC')
            ->page($page, $limit)
            ->select();
    }

    /**
     * 获取未中奖用户总数
     */
    public static function getNonWinnersCount()
    {
        return self::where('is_winner', 0)->count();
    }

    /**
     * 批量创建用户
     */
    public static function batchCreate($count)
    {
        // 清空现有数据
        Db::query('truncate table ' . self::getTable());

        $users = [];
        for ($i = 1; $i <= $count; $i++) {
            $users[] = [
                'id' => $i,
                'nickname' => '用户' . $i,
                'phone' => '138000000000' + intval($i),
                'is_winner' => 0
            ];
        }

        return self::insertAll($users);
    }

    /**
     * 清空所有用户
     */
    public static function clearAll()
    {
        return self::truncate();
    }
}
